//
//  JZHLoginViewController.m
//  极致荟
//
//  Created by mac on 14-4-8.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHLoginViewController.h"
#import "JZHTabbarViewController.h"
#import "JZHTopicViewController.h"
#import "JZHActivityViewController.h"
#import "JZHMessageViewController.h"
#import "JZHFriendsCircleViewController.h"
#import "JZHMySelfViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "MMProgressHUD+HUDShowExtral.h"
#import "MMDrawerController.h"
#import "JZHActivityViewController.h"
#import "MMExampleLeftSideDrawerViewController.h"
#import "MMDrawerVisualState.h"
#import "MMExampleDrawerVisualStateManager.h"
#import "MMNavigationController.h"
#import "JZHAppDelegate.h"
#import "SVHTTPRequest.h"
#import "CRSA.h"
#import "MMProgressHUD+HUDShowExtral.h"
#import "JZHFocusType.h"
#import "JZHSocket.h"
#import "WXApi.h"
//#import "BRTBeaconSDK.h"
#pragma mark -
#pragma mark Private Interface
/*
                      _oo0oo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                   0\  =  /0
 *                 ___/`---'\___
 *               ,'\\|      |// `,
 *              / \\|||  :  |||// \
 *             / _||||| -:- |||||_ \
 *            |   | \\\  -  /// |   |
 *            | \_|  ``\---/ '' |_/ |
 *            \  .-\__  `-'  ___/-. /
 *          ___`. . ` /--.--\   `. .'___
 *       .""  '<  '.___\_<|>_/___. ' >'  "".
 *      | | :.  `- \`.;`\ _ /`;.'/  - `  : | |
 *      \  \  '_.   \_ __\ /__ _/   ._`    / /
 *  =====`-.____`.___ ,\_____/ , ____ .-`___.-'=====
 *                     =======
 *
 *
 */
@interface JZHLoginViewController ()
{
    NSMutableArray* _permissions;
}
@property (weak, nonatomic) IBOutlet UITextField *pass;
@property (weak, nonatomic) IBOutlet UITextField *user;
@property (nonatomic,strong) MMDrawerController * drawerController;
@end


#pragma mark -
#pragma mark Implementation
@implementation JZHLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.user setReturnKeyType:UIReturnKeyDone];
    self.user.delegate=self;
    self.pass.delegate=self;
    [self.pass setReturnKeyType:UIReturnKeyDone];
    //导航设置
    [self setNavigation];
   
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---导航----
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//导航条设置
-(void)setNavigation
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"title"] forBarMetrics:UIBarMetricsDefault];
    //设置左按钮
    self.navigationController.navigationBar.tintColor=[UIColor orangeColor];
    UIButton *backBut=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 54, 32)];
    [backBut setBackgroundImage:[UIImage imageNamed:@"lab_btn_bac_1k@2x"] forState:UIControlStateNormal];
    [backBut setImage:[UIImage imageNamed:@"lab_btn_bac_1k@2x"] forState:UIControlStateHighlighted];
    [backBut setTitle:@"返回" forState:UIControlStateNormal];
    [backBut addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [backBut.titleLabel setFont:[UIFont systemFontOfSize:14]];
    UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:backBut];
    [self.navigationItem setLeftBarButtonItem:backBarButton];
    //设置导航视图title
    //self.navigationItem.titleView=[DealTitle dealTitle:@"登陆"];
    
}
//返回
-(void)back:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark ---登录----
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self LoginAction:nil];
    return YES;
}
- (IBAction)LoginAction:(UIButton *)sender {
    /**
     *1.登录失败，进行提示
     *2.登录成功进入主页
     */
   
    //创建tabbar
    NSMutableDictionary *dic=[[ NSMutableDictionary alloc]init];
    [MMProgressHUD showWithStatus :@"登陆中..."];
    
    //加密
    CRSA* rsa= [CRSA shareInstance];
    [rsa importRSAKeyWithType:KeyTypePublic];
    [dic setObject:[rsa encryptByRsa:self.user.text withKeyType:KeyTypePublic] forKey:@"mobile"];
    [dic setObject:[rsa encryptByRsa:self.pass.text withKeyType:KeyTypePublic] forKey:@"password"];
    
//    [dic setObject:self.user.text forKey:@"mobile"];
//    [dic setObject:self.pass.text forKey:@"password"];
    if(self.user.text.length==11)
    {
        [dic setObject:@"mobile" forKey:@"loginType"];
    }else
    {
         [dic setObject:@"username" forKey:@"loginType"];
    }
    [HttpRequest httpRequestPost:JZHHTTPURL(@"member/login") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            NSLog(@"%@",data);
          [self dataJosn:data];
            
        }else
        {
            [MMProgressHUD dismissWithError:@"登陆失败"];
        }
        
    }];
  
  // [self loadtabview];
   
}

- (void)loadtabview
{
    NSDictionary *datadic=[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:[User defuceUser].userId],@"userId" ,nil];
    NSDictionary *messgedic=[[NSDictionary alloc] initWithObjectsAndKeys:@"userOnline",@"type",datadic,@"data", nil];
   NSData *jsondata=[NSJSONSerialization dataWithJSONObject:messgedic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *json=[[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
    
    [[JZHSocket deful:self] send:json];
    //包装成PHP的JSON格式
//    json=[json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    json=[json stringByReplacingOccurrencesOfString:@" " withString:@""];
//    json=[NSString stringWithFormat:@"'%@'",json];
    
    
    JZHTabbarViewController *tabVC = [JZHTabbarViewController shareInstance];
    //[tabVC.view setBackgroundColor:[UIColor redColor]];
    //创建controllers
    JZHTopicViewController *topicVC = [[JZHTopicViewController alloc] init];
    [topicVC setHidesBottomBarWhenPushed:YES];
    JZHFriendsCircleViewController *friendsVC = [[JZHFriendsCircleViewController alloc] init];
    [friendsVC setHidesBottomBarWhenPushed:YES];
    JZHMessageViewController *messageVC = [[JZHMessageViewController alloc] init];
    [messageVC setHidesBottomBarWhenPushed:YES];
    JZHMySelfViewController *myselfVC = [[JZHMySelfViewController alloc] init];
    [myselfVC setHidesBottomBarWhenPushed:YES];
    
    UINavigationController *topicNav = [[UINavigationController alloc] initWithRootViewController:topicVC];
    
    
    
    UINavigationController *friendsNav = [[UINavigationController alloc] initWithRootViewController:friendsVC];
    UINavigationController *messageNav = [[UINavigationController alloc] initWithRootViewController:messageVC];
    UINavigationController *myselfNav = [[UINavigationController alloc] initWithRootViewController:myselfVC];
    
    
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    UIViewController * centerViewController = [[JZHActivityViewController alloc] init];
    [centerViewController setHidesBottomBarWhenPushed:YES];
    UINavigationController * navigationController = [[UINavigationController alloc] initWithRootViewController:centerViewController];
    
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    
    
    NSArray *vcArrays = [NSArray arrayWithObjects:topicNav,navigationController,friendsNav,messageNav,myselfNav, nil];
    tabVC.viewControllers = vcArrays;
    
    [[UIApplication sharedApplication] keyWindow].rootViewController = tabVC;
    

}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
#pragma mark --QQ登录--
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
- (IBAction)QQLoginAction:(UIButton *)sender {
 
   // [MMProgressHUD showProgressWithStyle:MMProgressHUDProgressStyleIndeterminate title:@"df" status:@"f"];
    ///RSA加密
  
    
    
     [ShareSDK getUserInfoWithType:ShareTypeTencentWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
        
        if(result)
        {
            int sex=0;
            if(userInfo.gender==0)
            {
                sex=1;
            }
            else if (userInfo.gender==1)
            {
                sex=0;
            }else
            {
                sex=1;
            }
            [self sanfang:@"tencentwb" sex:sex name:userInfo.nickname uid:userInfo.uid];
            
        }
    }];
 
 
}
- (IBAction)sina:(id)sender
{
    [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
        
        if(result)
        {
         
            int sex=0;
            if(userInfo.gender==0)
            {
                sex=1;
            }
            else if (userInfo.gender==1)
            {
                sex=0;
            }else
            {
                sex=1;
            }
            [self sanfang:@"sina" sex:sex name:userInfo.nickname uid:userInfo.uid];
        }
    }];
}
- (IBAction)wxload:(id)sender
{
//    [ShareSDK getUserInfoWithType:ShareTypeQQ authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
//        
//        if(result)
//        {
//            NSLog(@"%@",[userInfo nickname]);
//        }
//    }];

    SendAuthReq *rep=[[SendAuthReq alloc] init];
   
    rep.scope=@"snsapi_userinfo";
    rep.state=@"7878";
    [WXApi sendReq:rep];
}

- (void)sanfang:(NSString *)type sex:(int)sex name:(NSString *)name uid:(NSString *)uid
{
    NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:type,@"loginType",[NSNumber numberWithInt:sex],@"Sex",name,@"name",uid,@"connectId", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"member/login") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            NSLog(@"%@",data);
            [self dataJosn:data];
        }
    }];
}

- (void)dataJosn:(id)data
{
    
    NSDictionary *dic=[[data objectForKey:@"data"] objectForKey:@"userInfo"];
    [User defuceUser].pathHead=[[data objectForKey:@"data"]objectForKey:@"imgPrefix"];
    [User defuceUser].userId=[[dic objectForKey:@"userId"] intValue];
    [User defuceUser].name=[dic objectForKey:@"userName"];
    
    //公司名称
    [User defuceUser].company=[dic objectForKey:@"Company"];
    
    //动态
    [User defuceUser].isStr=[dic objectForKey:@"Sign"];
    
    //性别
    if([dic objectForKey:@"sex"]==[NSNull null])
    {
        [User defuceUser].sex=1;
    }else if([[dic objectForKey:@"sex"] intValue]==0)
    {
        [User defuceUser].sex=0;
    }else
    {
        [User defuceUser].sex=1;
    }
    //出生日期
    if([dic objectForKey:@"Birthday"]==[NSNull null])
    {
        [User defuceUser].userdate=[NSDate date];
    }else
    {
        [User defuceUser].userdate=[NSDate dateWithTimeIntervalSince1970:[[dic objectForKey:@"Birthday"] longLongValue]];
    }
    
    [User defuceUser].phone=[dic objectForKey:@"Mobile"];
    [User defuceUser].vip=[[dic objectForKey:@"vip"] intValue];
    [User defuceUser].userHeadImage=[[User defuceUser].pathHead stringByAppendingString:[dic objectForKey:@"avatar"] ];
    JZHFocusType *tf=[[JZHFocusType alloc]init];
    tf.focusType=5;
    tf.selectft=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:[[dic objectForKey:@"attention"] intValue]],@"id", nil];
    [User defuceUser].focusType=tf;
    
    //行业
    [User defuceUser].persdic=[[NSDictionary alloc]initWithObjectsAndKeys:[dic objectForKey:@"professionId"],@"id",[dic objectForKey:@"professionName"],@"name" ,nil];
    
    //职位
    [User defuceUser].jobdic=[[NSDictionary alloc]initWithObjectsAndKeys:[dic objectForKey:@"jobId"],@"id",[dic objectForKey:@"jobName"] ,@"name",nil];
    NSMutableDictionary * citdic=[[NSMutableDictionary alloc] init];
    
    if([dic objectForKey:@"areaId"]==[NSNull null])//城区id
    {
        [citdic setObject:[NSNumber numberWithInt:0] forKey:@"quid"];
    }else
    {
        [citdic setObject:[dic objectForKey:@"areaId"] forKey:@"quid"];
    }
    
    if([dic objectForKey:@"areaName"]==[NSNull null])//城区名称
    {
        [citdic setObject:@"" forKey:@"quid"];
    }else
    {
        [citdic setObject:[dic objectForKey:@"areaName"] forKey:@"quName"];
    }
    
    if([dic objectForKey:@"cityId"]==[NSNull null])//城市id
    {
        [citdic setObject:[NSNumber numberWithInt:0] forKey:@"cid"];
    }else
    {
        [citdic setObject:[dic objectForKey:@"cityId"] forKey:@"cid"];
    }
    
    if([dic objectForKey:@"cityName"]==[NSNull null])//城市名称
    {
        [citdic setObject:@"未选择" forKey:@"cityName"];
    }else
    {
        [citdic setObject:[dic objectForKey:@"cityName"] forKey:@"cityName"];
    }
    
    
    [User defuceUser].address=[[NSMutableArray alloc] init];
    
    
    [User defuceUser].locationdic=citdic;
    
    [[User defuceUser].locationmanager startUpdatingLocation];
    [self loadtabview];
}
@end
